<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { Warning } from '@element-plus/icons-vue'
import { defaultGroupFormData, formRules } from '../index'
import type { CustomDialogInstance, DictionaryGroupInfo } from '@/types'

import { queryTreeList } from '@/api/modules/sysDictionaryGroup'
// ------------------use------------------
// #region
defineProps<{
  title: string
  isEdit?: boolean
}>()
const emits = defineEmits<{
  'save-success': []
}>()
const formData = defineModel<any>('data', {
  default: () => defaultGroupFormData,
})

const [dictionaryData, setDictionaryData] = useState<
  DictionaryGroupInfo[]
>([])

const dialogRef = ref<CustomDialogInstance | null>(null)
const formRef = ref<FormInstance | null>(null)

const [parentCode, setParentCode] = useState('')

async function getDepartmentData() {
  const { data: res } = await queryTreeList()
  setDictionaryData(res)
}
async function open() {
  setParentCode('')
  formRef.value?.resetFields()
  await nextTick()
  dialogRef.value?.open?.()
  getDepartmentData()
}
function close() {
  dialogRef.value?.close?.()
}
async function clickSave(done: () => void) {
  try {
    await formRef.value?.validate()
    emits('save-success')
  }
  catch (error) {
    done()
  }
}

function findDicCodeByIdRecursively(
  id: number,
  dicts: DictionaryGroupInfo[],
): string {
  for (const dict of dicts) {
    if (dict.id === id) {
      return dict.dicCode
    }
    if (dict.children && dict.children.length > 0) {
      const code = findDicCodeByIdRecursively(id, dict.children)
      if (code) {
        return code
      }
    }
  }
  return ''
}

watchEffect(() => {
  const parentId = unref(formData).parentId
  if (parentId) {
    const code = findDicCodeByIdRecursively(parentId, unref(dictionaryData))
    setParentCode(code)
  }
  else {
    setParentCode('')
  }
})

watch(
  () => unref(parentCode),
  (code: string) => {
    if (code) {
      // console.log(code, formData.value.dicCode, formData.value.dicCode?.replace(code + '-', ''))
      formData.value.dicCode = formData.value.dicCode?.replace(`${code}-`, '')
    }
  },
)

// #endregion
defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    :title="title"
    width="600px"
    @confirm="clickSave"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="right"
      class="width-fill flex-direction align-center flex"
    >
      <el-form-item class="width-fill">
        <template #label>
          <span class="align-center flex">
            所属字典
            <el-tooltip
              content="不选默认为最高级字典"
              placement="top"
            >
              <el-icon
                class="c-pointer fs-16 margin-left-xs"
              >
                <Warning />
              </el-icon>
            </el-tooltip>
          </span>
        </template>
        <el-cascader
          v-model="formData.parentId"
          placeholder="请选择字典"
          :options="dictionaryData as any[]"
          :props="{
            label: 'dicName',
            value: 'id',
            emitPath: false,
            checkStrictly: true,
          }"
          filterable
          class="width-fill"
          :clearable="true"
        />
      </el-form-item>
      <el-form-item
        prop="dicName"
        label="字典名称"
        class="width-fill"
      >
        <el-input
          v-model.trim="formData.dicName"
          maxlength="20"
          clearable
          placeholder="请输入字典名称"
        />
      </el-form-item>
      <el-form-item
        prop="dicCode"
        label="字典编码"
        class="width-fill"
      >
        <el-input
          v-model.trim="formData.dicCode"
          :disabled="isEdit"
          maxlength="20"
          clearable
          placeholder="请输入字典编码"
          class="dic-code-input"
        >
          <template v-if="parentCode" #prepend>
            {{ parentCode }}
          </template>
        </el-input>
      </el-form-item>
    </el-form>
  </CustomDialog>
</template>

<style lang="scss" scoped>
.dic-code-input {
  :deep(.el-input-group__prepend) {
    padding-left: 11px;
    padding-right: 11px;
  }
}
</style>
